import os
import re
import tempfile


class PreProcessor:
    def __init__(self, filename):
        """初始化，读取文件内容"""
        with open(filename, "r", encoding="utf-8") as file:
            self.content = file.readlines()  # 按行读取内容
        self.results = []  # 保存处理后的结果
        self.discards = []
        self.current = None  # 当前正在处理
        self.pointer = -1  # 当前正在处理行的行号

        temp_dir = tempfile.gettempdir()
        self.output_file = os.path.join(temp_dir, "pre_processor_temp.txt")
        self.discard_file = os.path.join(temp_dir, "pre_processor_dicard.txt")

        self.clear_escape()

    def clear_escape(self):
        for idx,value in enumerate(self.content):
            self.content[idx] = value.replace("&", "")

    # 这个由子类继承，必须要使索引步进，否则陷入死循环
    def process_current(self):
        pass

    def process(self):
        while True:
            # 获取下一行
            if self.next() == False:
                break

            # 如果是空行，跳过
            if len(self.current) == 0:
                continue

            self.process_current()
        pass

    def save(self):
        with open(self.output_file, "w", encoding="utf-8") as f:
            for line in self.results:
                f.write(f"{line}\n")  # 每次写入一行
        with open(self.discard_file, "w", encoding="utf-8") as f:
            for line in self.discards:
                f.write(f"{line}\n")  # 每次写入一行

    # 将此行保存到结果，然后处理下一行
    def keep(self):
        self.results.append(self.current)

    def keep_text(self, text):
        self.results.append(text)

    # 将此行移动到Discard，然后处理下一行
    def discard(self):
        self.discards.append(self.current)

    # 将指针移到下一行
    def next(self):
        self.pointer += 1
        if self.pointer >= len(self.content):
            self.current = None
            return False
        else:
            self.current = self.content[self.pointer].strip()
            return True

    def startswith(self, text):
        return self.current.startswith(text)

    def contain(self, text):
        return text in self.current

    def pick_str(self, text, pattern):
        match = re.search(pattern, text)
        if match:
            return str(match.group(1))
        return None

    def clear_temp(self):
        os.remove(self.output_file)
        os.remove(self.discard_file)
